package com.piggymetrics.statistics.mongo.service;

import com.gaea.tracker.ServiceTracker;
import com.gaea.tracker.common.Identifier;
import com.piggymetrics.statistics.mongo.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.mongo.repository.DataPointRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class StatisticsMongoService {
  ThreadLocal<ServiceTracker> trackerThreadLocal = new ThreadLocal<ServiceTracker>();


  @Autowired
  private DataPointRepository dataPointRepository;

  public List<DataPoint> findByAccountName(String accountName){
    readInfo();
    if ( trackerThreadLocal.get() == null ){
      trackerThreadLocal.set(ServiceTracker.newInstance("statistics-mongo-service"));
    }
    ServiceTracker tracker = trackerThreadLocal.get();
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getRequest();
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getResponse();
    tracker.trackInEvent(request, response);

    List<DataPoint> list = dataPointRepository.findByIdAccount(accountName);

    tracker.trackBackOutEvent(response);
    return list;
  }

  public String save(DataPoint dataPoint){
    readInfo();
    if ( trackerThreadLocal.get() == null ){
      trackerThreadLocal.set(ServiceTracker.newInstance("statistics-mongo-service"));
    }
    ServiceTracker tracker = trackerThreadLocal.get();
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getRequest();
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getResponse();
    tracker.trackInEvent(request, response);

    dataPointRepository.save(dataPoint);

    tracker.trackBackOutEvent(response);
    return "void";
  }

  private void readInfo(){
    try {
      Process process = null;
      List<String> processList = new ArrayList<String>();
      try {
        process = Runtime.getRuntime().exec("uptime");
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = input.readLine()) != null) {
          processList.add(line);
        }
        input.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      String[] strings = processList.get(0).split(" ");
      boolean isAverage = false;
      for (String s : strings){
        if ( isAverage ){
          long returnVal = Double.valueOf(s.substring(0, s.length() - 1)).longValue();
          Thread.sleep(returnVal / 5);
          break;
        }
        if ( s.length() > 2 && s.substring(0,s.length() - 1).equals("average") ){
          isAverage = true;
        }
      }
    }catch (InterruptedException e){
      Arrays.toString(e.getStackTrace());
    }
  }
}
